//
//  SharMapViewController.m
//  SXH
//
//  Created by 龚啸 on 16/2/17.
//  Copyright © 2016年 lyss. All rights reserved.
//

#import "SharMapViewController.h"
#import "CommonService.h"
#import "SVProgressHUD.h"
#import "JSONModel.h"
#import "UIImageView+WebCache.h"
#import "DXAlertView.h"
#import "MFMessageComposeViewController+extension.h"
#import "WXApi.h"
#import "ShareModel.h"
#import "RouteAnnotation.h"
#define kRadianToDegrees(radian) (radian*180.0)/(M_PI)
typedef void(^MissOrBackBlock)();
@interface ShareEntity : JSONModel

@property (nonatomic,copy) NSString *user_face;
@property (nonatomic,strong) NSString *longitude;
@property (nonatomic,strong) NSString *latitude;
@property (nonatomic,copy) NSString *nickname;

@end
@implementation ShareEntity

@end


@interface UserAnnotation : BMKPointAnnotation
@property (nonatomic, strong) ShareEntity *shareEntity;
@property (nonatomic, copy) NSString *imgString;
@property (nonatomic,assign)NSInteger time;
@end
@implementation UserAnnotation

-(void)setShareEntity:(ShareEntity *)shareEntity
{
    _imgString = [NSString stringWithFormat:@"%@/%@",IMAGE_URL,shareEntity.user_face];
    CLLocationDegrees latitude = [shareEntity.latitude doubleValue];
    CLLocationDegrees longtitude = [shareEntity.longitude doubleValue];
    CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(latitude, longtitude);
    self.coordinate = coord;
    _shareEntity = shareEntity;
}
@end
typedef void(^AnnotationBlock)(UserAnnotation *anno);
@interface SharMapViewController ()<MFMessageComposeViewControllerDelegate>{
    NSTimer *timer;
    NSString *room_num;
    NSMutableArray *array;
    NSMutableArray * mutableArrayShare;
    BMKRouteSearch* _routesearch;
    int zoom;
    int i ;
    int angle;
    UserAnnotation *selectAnnotation;
    UITapGestureRecognizer *rec;
    NSString *copyString;
    UIView *coverView;;
}


@property (weak, nonatomic) IBOutlet UIView *viewCollection;
@property (weak, nonatomic) IBOutlet UILabel *labelTitle;
@property (weak, nonatomic) IBOutlet UIButton *rightBtn;
@property (strong, nonatomic) IBOutlet UIView *popView;
@property (weak, nonatomic) IBOutlet UILabel *locationTitle;
@property (nonatomic, strong) MissOrBackBlock missOrBackBlock;
@property (weak, nonatomic) IBOutlet UIButton *refreshBtn;
@property (weak, nonatomic) IBOutlet UILabel *labelDistance;
@property (weak, nonatomic) IBOutlet UILabel *labelTime;
@property (weak, nonatomic) IBOutlet UILabel *name;
@property (nonatomic, strong) BMKGeoCodeSearch*searcher;
@property (nonatomic, strong) AnnotationBlock annotationBlock;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightConstraint;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionViewImage;
@property (strong, nonatomic) IBOutlet UIView *shareView;
@property (weak, nonatomic) IBOutlet UIButton *btnWeixin;
@property (weak, nonatomic) IBOutlet UIButton *btnFriend;
@property (weak, nonatomic) IBOutlet UIButton *btnSns;
@end
 static NSString * CellIdentifier = @"UICollectionViewCell";

@implementation SharMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    selectAnnotation = [[UserAnnotation alloc]init];
    rec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissPopView)];
    angle = 0;
    mutableArrayShare = [NSMutableArray array];
     self.labelTitle.text = [NSString stringWithFormat:@"房间：%@",_room_id];
    array = [NSMutableArray array];
    self.fd_interactivePopDisabled = YES;
//    NSMutableArray *arr = [NSMutableArray array];
  
    if ([_created isEqualToString:_userId]) {
       
        [_rightBtn setTitle:@"解散退出" forState:UIControlStateNormal];
    }else{
       
        [_rightBtn setTitle:@"退出房间" forState:UIControlStateNormal];
    }
    
    [self initMap];
    [self reFresh];
    [self initCollection];
    timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(reFresh) userInfo:nil repeats:YES];
    i = 0;
    copyString = [NSString stringWithFormat:@"#乐游口令#长按复制这条消息，打开乐游即可看到【%@邀请你加入位置共享，进群口令%@】记得更新到最新版的乐游哦",[UserEntity sharedInstance]
.nickName,_room_id];
}
-(void)initCollection
{
//    [_collectionViewImage registerNib:[UINib nibWithNibName:@"UICollectionViewCell" bundle:nil] forCellWithReuseIdentifier:CellIdentifier];
     [_collectionViewImage registerClass:[UICollectionViewCell  class] forCellWithReuseIdentifier:CellIdentifier];
    _collectionViewImage.backgroundColor = [UIColor clearColor];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    //横向
    [flowLayout setMinimumInteritemSpacing:0.0f];
    //AllLine
    [flowLayout setMinimumLineSpacing:5.0f];
    _viewCollection.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.6];
    [_collectionViewImage setCollectionViewLayout:flowLayout];

}
-(void)viewWillAppear:(BOOL)animated {
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    _locService.delegate = self;
    _routesearch.delegate = self;
    _searcher.delegate = self;
    [super viewWillAppear:animated];
    
    [MobClick beginLogPageView:@"SharMapViewController"];
}
- (IBAction)backAndMiss:(id)sender {
    if ([_created isEqualToString:_userId]) {
            [self detroyRoom];
    }else{
            [self exitRoom];
    }
}

-(void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    _locService.delegate = nil;
    _searcher.delegate = nil;
    _routesearch.delegate =  nil;
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"SharMapViewController"];

}

- (void)dealloc {
    if (_mapView) {
        _mapView = nil;
    }
}
-(void)initMap
{
    _mapView.isSelectedAnnotationViewFront = YES;
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
     zoom = 16;
    [_mapView setZoomLevel:zoom+0.3];
//    [_mapView setCenterCoordinate:location.coordinate animated:YES];
    [_mapView setCenterCoordinate:_userLocation.coordinate animated:YES];
    _searcher =[[BMKGeoCodeSearch alloc]init];
    
    _routesearch = [[BMKRouteSearch alloc]init];
    
   }
/**
 *  刷新状态
 */

-(void)reFresh
{
    [_locService startUserLocationService];
}
//退出房间
-(void)exitRoom
{
    CommonService *service = [[CommonService alloc] init];
    DXAlertView * alert = [[DXAlertView alloc] initWithTitle:@"提示" contentText:@"确定退出房间？" leftButtonTitle:@"取消" rightButtonTitle:@"确定"];
        alert.leftBlock = ^() {
            DebugLog(@"取消退出");
        };
        alert.rightBlock = ^() {
            NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:_room_id,@"room_id",_userId,@"user_id",nil];
            [service getNetWorkData:dict Path:BACK_GROUP Successed:^(id entity) {
                NSDictionary *dic = (NSDictionary *)entity ;
                NSInteger code = [[dic objectForKey:@"code"] integerValue];
                if (code == 0) {
                    [timer invalidate];
                    [self.navigationController popViewControllerAnimated:YES];
                }else{
                    [SVProgressHUD showErrorWithStatus:@"退出房间失败"];
                }
                
            } Failed:^(NSInteger errorCode, NSString *message) {
                 [SVProgressHUD showErrorWithStatus:@"退出房间失败"];
            }];
    
        };
        [alert show];
}
//销毁房间
-(void)detroyRoom
{
    CommonService *service = [[CommonService alloc] init];

    DXAlertView * alert = [[DXAlertView alloc] initWithTitle:@"提示" contentText:@"确定解散并退出房间？" leftButtonTitle:@"取消" rightButtonTitle:@"确定"];
    alert.leftBlock = ^() {
        DebugLog(@"取消解散");
    };
    alert.rightBlock = ^() {
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:_room_id,@"room_id",_userId,@"user_id",nil];
        [service getNetWorkData:dict Path:DETRY_RGROUP Successed:^(id entity) {
            NSDictionary *dic = (NSDictionary *)entity ;
            NSInteger code = [[dic objectForKey:@"code"] integerValue];
            if (code == 0) {
//
                [timer invalidate];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [SVProgressHUD showErrorWithStatus:@"解散并退出房间失败"];
            }
            
        } Failed:^(NSInteger errorCode, NSString *message) {
            [SVProgressHUD showErrorWithStatus:@"解散并退出房间失败"];
        }];

    };
    [alert show];
}
- (IBAction)doBack:(id)sender {
        [timer invalidate];
        [self.navigationController popViewControllerAnimated:YES];
    
}
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [_locService stopUserLocationService];
    DebugLog(@"刷新============");
    DebugLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    _userLocation = userLocation.location;
     [_mapView updateLocationData:userLocation];
     NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:_room_id,@"room_id",_userId,@"user_id",[NSString stringWithFormat:@"%f",userLocation.location.coordinate.longitude],@"longitude",[NSString stringWithFormat:@"%f",userLocation.location.coordinate.latitude],@"latitude",nil];
    
    CommonService *service = [[CommonService alloc]init];
    [service getNetWorkData:param Path:REFRESH_GROUP Successed:^(id entity) {
        NSDictionary *dic = (NSDictionary *)entity;
         _refreshBtn.enabled = YES;
        [self.view.layer removeAllAnimations];
    
        NSMutableArray * padic = [dic objectForKey:@"data"];
        if (!padic) {
            return ;
        }
        [_mapView removeAnnotations:_mapView.annotations];
        [mutableArrayShare removeAllObjects];
        for (int k = 0 ;k<[padic count]; k++) {
            
            ShareEntity *entity = [[ShareEntity alloc]initWithDictionary:padic[k] error:nil] ;
            UserAnnotation *annotiation = [[UserAnnotation alloc] init];
            annotiation.shareEntity = entity;
            annotiation.time = [[dic objectForKey:@"time"] integerValue];
            [mutableArrayShare addObject:annotiation];
            
            [_mapView addAnnotation:annotiation];
        }
        [_collectionViewImage reloadData];

        
    } Failed:^(NSInteger errorCode, NSString *message) {
        
        i++;
        if (i == 2 ) {
            [timer invalidate];
        }
        [SVProgressHUD showErrorWithStatus:@"更新位置失败，请检查网络或定位服务"];
    }];
}
- (void)setAnnotions
{
    [_mapView removeAnnotations:_mapView.annotations];
}
-(BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation
{
    NSString *AnnotationViewID = @"ClusterMark";
    UserAnnotation *anno = (UserAnnotation*)annotation;
    BMKAnnotationView *annotationView = [[BMKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
    
    annotationView.canShowCallout = NO;//在点击大头针的时候会弹出那个黑框框
    annotationView.draggable = NO;//禁止标注在地图上拖动
    annotationView.annotation = anno;
//    annotationView.image = [UIImage imageNamed:@"placehodeLoading.png"];
    
    UIView *viewForImage=[[UIView alloc]init];
    UIImageView *imageview=[[UIImageView alloc]init];
    if(iPhone6Plus){
        [viewForImage setFrame:CGRectMake(0, 0, 150, 150)];
        [imageview setFrame:CGRectMake(0, 0, 150, 150)];
    }else{
        [viewForImage setFrame:CGRectMake(0, 0, 70, 70)];
        [imageview setFrame:CGRectMake(0, 0, 70, 70)];
    }

    [imageview sd_setImageWithURL:[NSURL URLWithString:anno.imgString] placeholderImage:[UIImage imageNamed:@"placehodeLoading.png"] options:SDWebImageLowPriority | SDWebImageRetryFailed completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
     {
         annotationView.image=[self getImageFromView:viewForImage];//修改默认图片不替换问题
     }];

    imageview.layer.masksToBounds=YES;
    imageview.layer.cornerRadius = imageview.bounds.size.width/2;

    [viewForImage addSubview:imageview];
    annotationView.image=[self getImageFromView:viewForImage];
   
    return annotationView;

}

-(UIImage *)getImageFromView:(UIView *)view{
    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (IBAction)zoomBig:(id)sender {
    if (zoom++ > 20 ) {
        return;
    }
    [_mapView setZoomLevel:zoom];
    
}

- (IBAction)zoomSmall:(id)sender {
    if (zoom-- < 7) {
        return;
    }
    [_mapView setZoomLevel:zoom];
    
}
- (IBAction)showLocation:(id)sender {
//    _mapView.showsUserLocation = YES;
   
    [_mapView setCenterCoordinate:_userLocation.coordinate animated:YES];
}
-(void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view
{
    UserAnnotation * anno = (UserAnnotation*) view.annotation;
    //发起反向地理编码检索
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){anno.coordinate.latitude,anno.coordinate.longitude};
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeoCodeSearchOption.reverseGeoPoint = pt;
    BOOL flag = [_searcher reverseGeoCode:reverseGeoCodeSearchOption];
    
    if(flag)
    {
        NSLog(@"反geo检索发送成功");
       
    }
    else
    {
//        NSLog(@"反geo检索发送失败");
    }
    [_mapView deselectAnnotation:view.annotation animated:YES];
     [self showWithEntity:anno];
    selectAnnotation = anno;
    
}
//接收反向地理编码结果
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:
(BMKReverseGeoCodeResult *)result
                        errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        _locationTitle.text = result.address;
    }
    else {
        NSLog(@"抱歉，未找到结果");
    }
}

-(void)mapView:(BMKMapView *)mapView didDeselectAnnotationView:(BMKAnnotationView *)view{
    NSLog(@"deselect");
}
-(void)showWithEntity:(UserAnnotation *)anno
{
    [_mapView addGestureRecognizer:rec];
    double la1 = _userLocation.coordinate.latitude;
    double lo1 = _userLocation.coordinate.longitude;
    double la2 = [anno.shareEntity.latitude doubleValue];
    double lo2 = [anno.shareEntity.longitude doubleValue];
    BMKMapPoint point1 = BMKMapPointForCoordinate(CLLocationCoordinate2DMake(la1,lo1));
    BMKMapPoint point2 = BMKMapPointForCoordinate(CLLocationCoordinate2DMake(la2,lo2));
    CLLocationDistance distance = BMKMetersBetweenMapPoints(point1,point2);
    if (distance == 0) {
        _labelDistance.text = [NSString stringWithFormat:@"0米"];

    }else if (distance/1000 >= 1) {
        _labelDistance.text = [NSString stringWithFormat:@"%.2f千米",distance/1000];

    }else{
        _labelDistance.text = [NSString stringWithFormat:@"%.0f米",distance];
    }
    _name.text = anno.shareEntity.nickname;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:anno.time];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    _labelTime.text = [formatter stringFromDate:date];
    
    if ([self.view.subviews containsObject:_popView]) {
        [UIView animateWithDuration:0.5 animations:^{
            _popView.layer.transform =CATransform3DMakeTranslation(0, -110, 0);
            _heightConstraint.constant = 52 +60;
            [self loadViewIfNeeded];
        }];
        
        
    }else{
        
        
        _popView.frame = CGRectMake(8, ScreenHeight, ScreenWidth -16, 105);
        [self.view addSubview:_popView];
        [UIView animateWithDuration:0.5 animations:^{
            _popView.layer.transform = CATransform3DMakeTranslation(0, -110, 0);
            _heightConstraint.constant = 52 +60;
            [self loadViewIfNeeded];
        } completion:nil];
    }
    
}
- (IBAction)refresh:(id)sender {
//    [self startAnimation];
     [_refreshBtn.layer addAnimation:[self rotation:0.5 degree:kRadianToDegrees(90) direction:1 repeatCount:MAXFLOAT] forKey:nil];
    [self reFresh];
    //旋转动画。
   
    _refreshBtn.enabled = NO;
}
#pragma mark ====旋转动画======
-(CABasicAnimation *)rotation:(float)dur degree:(float)degree direction:(int)direction repeatCount:(int)repeatCount
{
    CATransform3D rotationTransform = CATransform3DMakeRotation(degree, 0, 0, direction);
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    animation.toValue = [NSValue valueWithCATransform3D:rotationTransform];
    animation.duration  =  dur;
    animation.autoreverses = NO;
    animation.cumulative = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = repeatCount;
    animation.delegate = self;
    
    return animation;
    
}
-(void)dismissPopView{
    DebugLog(@"dismissPopView");
    [_mapView removeGestureRecognizer:rec];
    [_mapView deselectAnnotation:selectAnnotation animated:YES];
    if ([self.view.subviews containsObject:_popView]) {
        [UIView animateWithDuration:0.5 animations:^{
            _popView.layer.transform =CATransform3DIdentity;
            _heightConstraint.constant = 52 ;
            [self loadViewIfNeeded];
        }];
        
    }
}
//-(void) startAnimation
//{
//    [UIView beginAnimations:nil context:nil];
//    [UIView setAnimationDuration:0.01];
//    [UIView setAnimationDelegate:self];
//    [UIView setAnimationDidStopSelector:@selector(endAnimation)];
//    _refreshBtn.transform = CGAffineTransformMakeRotation(angle * (M_PI / 180.0f));
//    [UIView commitAnimations];
//}
//
//-(void)endAnimation
//{
//    angle += 10;
//    [self startAnimation];

- (IBAction)doNavigation:(id)sender {

//    //发起导航
//   
//        //节点数组
//        NSMutableArray *nodesArray = [[NSMutableArray alloc]    initWithCapacity:2];
//        
//        //起点
//        BNRoutePlanNode *startNode = [[BNRoutePlanNode alloc] init];
//        startNode.pos = [[BNPosition alloc] init];
////        startNode.pos.x = 113.936392;
////        startNode.pos.y = 22.547058;
//    
//    startNode.pos.x = _userLocation.location.coordinate.longitude;
//    startNode.pos.y = _userLocation.location.coordinate.latitude;
//        startNode.pos.eType = BNCoordinate_BaiduMapSDK;
//        [nodesArray addObject:startNode];
//        
//        //终点
//        BNRoutePlanNode *endNode = [[BNRoutePlanNode alloc] init];
//        endNode.pos = [[BNPosition alloc] init];
////        endNode.pos.x = 114.077075;
////        endNode.pos.y = 22.543634;
////    
//    endNode.pos.x = [selectAnnotation.shareEntity.longitude doubleValue];
//    endNode.pos.y = [selectAnnotation.shareEntity.latitude doubleValue];
//        endNode.pos.eType = BNCoordinate_BaiduMapSDK;
//        [nodesArray addObject:endNode];
//        //发起路径规划
//        [BNCoreServices_RoutePlan startNaviRoutePlan:BNRoutePlanMode_Recommend naviNodes:nodesArray time:nil delegete:self userInfo:nil];
    
    
    
    BMKOpenTransitRouteOption *opt = [[BMKOpenTransitRouteOption alloc] init];
    opt.appScheme = @"baidumapsdk://mapsdk.baidu.com";//用于调起成功后，返回原应用
    //初始化起点节点
    BMKPlanNode* start = [[BMKPlanNode alloc]init];
    //指定起点经纬度
    CLLocationCoordinate2D coor1;
    coor1.latitude = 39.90868;
    coor1.longitude = 116.204;
    //指定起点名称
    start.name = @"我的位置";
    start.pt = _userLocation.coordinate;
    //指定起点
    opt.startPoint = start;
    
    //初始化终点节点
    BMKPlanNode* end = [[BMKPlanNode alloc]init];
    CLLocationCoordinate2D coor2;
    coor2.latitude = [selectAnnotation.shareEntity.latitude doubleValue];
    coor2.longitude = [selectAnnotation.shareEntity.longitude doubleValue];
    end.pt = coor2;
    //指定终点名称
    end.name = @"终点";
    opt.endPoint = end;
    
    
    if ([[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:@"baidumap://map/"]]) {
        NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin=latlng:%f,%f|name:我的位置&destination=latlng:%f,%f|name:终点&mode=driving",_userLocation.coordinate.latitude, _userLocation.coordinate.longitude,coor2.latitude,coor2.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlString]];
    }
    else {
//        打开地图公交路线检索
            BMKOpenErrorCode code = [BMKOpenRoute openBaiduMapTransitRoute:opt];
    }
    
    
    


}
//-(void)routePlanDidFinished:(NSDictionary *)userInfo
//{
//    NSLog(@"算路成功");
//    
//    //路径规划成功，开始导航
//    [BNCoreServices_UI showNaviUI: BN_NaviTypeReal delegete:self isNeedLandscape:YES];
//}
- (void) walkRoute {
    BMKPlanNode* end = [[BMKPlanNode alloc]init];
    end.pt = (CLLocationCoordinate2D){[selectAnnotation.shareEntity.latitude doubleValue],[selectAnnotation.shareEntity.longitude doubleValue]};
    BMKPlanNode* start = [[BMKPlanNode alloc]init];
    start.name = @"我的位置";
    start.cityName = [[NSUserDefaults standardUserDefaults] valueForKey:SelectedCityName];
    start.pt = _userLocation.coordinate;
    
    
    DebugLog(@"start: %f, %f", start.pt.latitude, start.pt.longitude);
    
    end.cityName = [[NSUserDefaults standardUserDefaults] valueForKey:SelectedCityName];
    
    DebugLog(@"end: %f, %f", end.pt.latitude, end.pt.longitude);
    
    BMKWalkingRoutePlanOption *walkingRouteSearchOption = [[BMKWalkingRoutePlanOption alloc]init];
    walkingRouteSearchOption.from = start;
    walkingRouteSearchOption.to = end;
    BOOL flag = [_routesearch walkingSearch:walkingRouteSearchOption];
    if(flag)
    {
        NSLog(@"walk检索发送成功");
    }
    else
    {
        [super showLoadingView:NO];
        NSLog(@"walk检索发送失败");
    }
}
- (void)onGetTransitRouteResult:(BMKRouteSearch*)searcher result:(BMKTransitRouteResult*)result errorCode:(BMKSearchErrorCode)error
{
    NSArray* array1 = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array1];
    array1 = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array1];
    if (error == BMK_SEARCH_NO_ERROR) {
        BMKTransitRouteLine* plan = (BMKTransitRouteLine*)[result.routes objectAtIndex:0];
        // 计算路线方案中的路段数目
        int size = [plan.steps count];
        int planPointCounts = 0;
        for (int k = 0; k < size; k++) {
            BMKTransitStep* transitStep = [plan.steps objectAtIndex:k];
            if (k==0) {
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.starting.location;
                item.title = @"起点";
                item.type = 0;
                [_mapView addAnnotation:item]; // 添加起点标注
                
            } else if(k==size-1) {
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.terminal.location;
                item.title = @"终点";
                item.type = 1;
                [_mapView addAnnotation:item]; // 添加起点标注
            }
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = transitStep.entrace.location;
            item.title = transitStep.instruction;
            item.type = 3;
            [_mapView addAnnotation:item];
            
            //轨迹点总数累计
            planPointCounts += transitStep.pointsCount;
        }
        
        //轨迹点
        BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
        int h = 0;
        for (int j = 0; j < size; j++) {
            BMKTransitStep* transitStep = [plan.steps objectAtIndex:j];
            int k=0;
            for(k=0;k<transitStep.pointsCount;k++) {
                temppoints[h].x = transitStep.points[k].x;
                temppoints[h].y = transitStep.points[k].y;
                i++;
            }
            
        }
        // 通过points构建BMKPolyline
        BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        [_mapView addOverlay:polyLine]; // 添加路线overlay
        delete []temppoints;
        [self mapViewFitPolyLine:polyLine];
    }
}
- (void)mapViewFitPolyLine:(BMKPolyline *) polyLine {
    CGFloat ltX, ltY, rbX, rbY;
    if (polyLine.pointCount < 1) {
        return;
    }
    BMKMapPoint pt = polyLine.points[0];
    ltX = pt.x, ltY = pt.y;
    rbX = pt.x, rbY = pt.y;
    for (int k = 1; k < polyLine.pointCount; k++) {
        BMKMapPoint pt = polyLine.points[k];
        if (pt.x < ltX) {
            ltX = pt.x;
        }
        if (pt.x > rbX) {
            rbX = pt.x;
        }
        if (pt.y > ltY) {
            ltY = pt.y;
        }
        if (pt.y < rbY) {
            rbY = pt.y;
        }
    }
    BMKMapRect rect;
    rect.origin = BMKMapPointMake(ltX , ltY);
    rect.size = BMKMapSizeMake(rbX - ltX, rbY - ltY);
    [_mapView setVisibleMapRect:rect];
    _mapView.zoomLevel = _mapView.zoomLevel - 0.3;

}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [mutableArrayShare count];
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    
    UserAnnotation * annotation = [mutableArrayShare objectAtIndex:indexPath.row];
    UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 34, 34)];
    image.layer.cornerRadius = 18;
    image.layer.masksToBounds = YES;
    [image sd_setImageWithURL:[NSURL URLWithString:annotation.imgString] placeholderImage:[UIImage imageNamed:@"placehodeLoading.png"]];
    [cell addSubview:image];
    return cell;
}
#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(34, 34);
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
 
    return UIEdgeInsetsMake(0, 0 , 0, 0);
    
    
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UserAnnotation *anno = [mutableArrayShare objectAtIndex:indexPath.row];
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){anno.coordinate.latitude,anno.coordinate.longitude};
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeoCodeSearchOption.reverseGeoPoint = pt;
    BOOL flag = [_searcher reverseGeoCode:reverseGeoCodeSearchOption];
    
    if(flag)
    {
        NSLog(@"反geo检索发送成功");
        
    }
    else
    {
//        NSLog(@"反geo检索发送失败");
    }

    
    [self showWithEntity:anno];
    selectAnnotation = anno;
}
//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (IBAction)shareAction:(id)sender {
    if (![self.view.subviews containsObject:coverView]) {
        coverView =[[UIView alloc]initWithFrame:self.view.bounds];
        coverView.backgroundColor = [UIColor blackColor];
        coverView.alpha = 0.1;
        UITapGestureRecognizer * ro = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchesCover)];
        [coverView addGestureRecognizer:ro];
        [self.view addSubview:coverView];
    }

    if (![self.view.subviews containsObject:_shareView]) {
        [self.view addSubview:_shareView];
        _shareView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, _shareView.frame.size.height);
        NSString * bundlePath = [[ NSBundle mainBundle] pathForResource: @"ShareSDKUI" ofType :@"bundle"];
        NSBundle  *bundle = [NSBundle   bundleWithPath :bundlePath];
        [_btnSns setBackgroundImage:[UIImage imageWithContentsOfFile:[bundle pathForResource:@"sns_icon_19" ofType:@"png" inDirectory:@"Icon"] ] forState:UIControlStateNormal];
        [_btnFriend setBackgroundImage:[UIImage imageWithContentsOfFile:[bundle pathForResource:@"sns_icon_23" ofType:@"png" inDirectory:@"Icon"]] forState:UIControlStateNormal];
        [_btnWeixin setBackgroundImage:[UIImage imageWithContentsOfFile:[bundle pathForResource:@"sns_icon_22" ofType:@"png" inDirectory:@"Icon"]] forState:UIControlStateNormal];
        
    }
    [self.view bringSubviewToFront:_shareView];
        [UIView animateWithDuration:0.5 animations:^{
        _shareView.layer.transform = CATransform3DMakeTranslation(0, -_shareView.bounds.size.height, 0);
    }];

}

-(void)touchesCover
{
    [coverView removeFromSuperview];
    [UIView animateWithDuration:0.5 animations:^{
        _shareView.layer.transform = CATransform3DIdentity;
    }];

    
}

- (IBAction)weixinShare:(id)sender {
    if (![WXApi isWXAppInstalled]) {
        [SVProgressHUD showErrorWithStatus:@"微信未安装"];
        return;
    }
    
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"分享口令" message:copyString delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去粘贴", nil];
    alert.tag = 1000;
    [alert show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1000) {
        if (buttonIndex == 1) {
            [[UIPasteboard generalPasteboard] setValue:copyString forPasteboardType:[UIPasteboardTypeListString objectAtIndex:0]];
            if (![WXApi openWXApp]) {
                DebugLog(@"111111");
            }
        }
    }
}
- (IBAction)friendShare:(id)sender {
    if (![WXApi isWXAppInstalled]) {
        [SVProgressHUD showErrorWithStatus:@"微信未安装"];
        return;
    }
    SendMessageToWXReq *req = [ [SendMessageToWXReq alloc] init];
    req.text = copyString;
    req.bText = YES;
    req.scene = WXSceneTimeline;
    if (![WXApi sendReq:req]) {
        //        [SVProgressHUD showErrorWithStatus:@"分享失败"];
    }
    
}
- (IBAction)messageShare:(id)sender {
    [self showMessageView:nil title:@"乐游口令" body:copyString];
}
-(void)showMessageView:(NSArray *)phones title:(NSString *)title body:(NSString *)body
{
    if( [MFMessageComposeViewController canSendText] )
    {
        
        MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc] init];
        //        UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:controller];
        controller.recipients = phones;
        controller.navigationBar.tintColor = [UIColor redColor];
        controller.body = body;
        
        controller.messageComposeDelegate = self;
        controller.navigationBar.hidden = NO;

        [[[[controller viewControllers] lastObject] navigationItem] setTitle:title];
        [controller setRightItem];
        [self presentViewController:controller animated:YES completion:nil];
        
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息"
                                                        message:@"该设备不支持短信功能"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil, nil];
        [alert show];
    }
}
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{
    
    [controller dismissModalViewControllerAnimated:NO];//关键的一句   不能为YES
    
    switch ( result ) {
            
        case MessageComposeResultCancelled:
            
            [self alertWithTitle:@"提示信息" msg:@"发送取消"];
            break;
        case MessageComposeResultFailed:// send failed
            [self alertWithTitle:@"提示信息" msg:@"发送成功"];
            break;
        case MessageComposeResultSent:
            [self alertWithTitle:@"提示信息" msg:@"发送失败"];
            break;
        default:
            break;
    }
}


- (void) alertWithTitle:(NSString *)title msg:(NSString *)msg1 {
    
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:msg1
                                                   delegate:self
                                          cancelButtonTitle:nil
                                          otherButtonTitles:@"确定", nil];
    
    [alert show];  
    
}

@end


